<template>
  <div>
    <van-cell @click="$emit('clickSearchSuggest',item)" v-for="(item,index) in suggestList" :key="index" icon="search">
      <template #title>
        <div v-html="formatStr(item)"></div>
      </template>
    </van-cell>
    <van-empty image="search" description="暂无建议" v-if="!suggestList.length" />
  </div>
</template>

<script>
import { getSearchSuggestAPI } from '@/api/search.js'
import { Toast } from 'vant'
// 根据搜索的值 来发请求 获取搜索建议
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestList: []
    }
  },
  watch: {
    searchText: {
      immediate: true,
      handler (newVal) {
        this.timer && clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.getSearchSuggestFn(newVal)
        }, 800)
      }
    }
  },
  methods: {
    async getSearchSuggestFn (keyword) {
      try {
        const { options: res } = await getSearchSuggestAPI(keyword)
        this.suggestList = res
      } catch (error) {
        Toast('获取建议失败')
      }
    },
    formatStr (str) {
      const reg = new RegExp(this.searchText, 'gi')
      return str.replace(reg, `<span style="color:red">${this.searchText}</span>`)
    }
  },
  beforeDestroy () {
    // 当输入框没有值时,会销毁这个组件,此时还存在上一个延时器没有清除,因此在这里清除延时器
    clearTimeout(this.timer)
  }
}
</script>

<style>

</style>
